package cn.qdu.controller;

import cn.qdu.model.Comment;
import cn.qdu.model.User;
import cn.qdu.service.PostService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    private PostService postService = new PostService();
    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            sendJsonResponse(response, false, "请先登录");
            return;
        }

        String postIdStr = request.getParameter("postId");
        String content = request.getParameter("content");

        if (postIdStr == null || content == null || content.trim().isEmpty()) {
            sendJsonResponse(response, false, "参数不完整");
            return;
        }

        try {
            int postId = Integer.parseInt(postIdStr);
            Comment comment = new Comment();
            comment.setPostId(postId);
            comment.setUserId(currentUser.getUserId());
            comment.setContent(content.trim());

            boolean success = postService.addComment(comment);
            if (success) {
                // 获取更新后的评论总数
                int commentCount = postService.getCommentCountByPostId(postId);

                Map<String, Object> data = new HashMap<>();
                data.put("success", true);
                data.put("commentId", comment.getCommentId());
                data.put("userNickname", currentUser.getNickname());
                data.put("userAvatar", currentUser.getAvatar());
                data.put("createdAt", System.currentTimeMillis());
                data.put("commentCount", commentCount); // 添加评论总数

                sendJsonResponse(response, data);
            } else {
                sendJsonResponse(response, false, "评论失败");
            }
        } catch (NumberFormatException e) {
            sendJsonResponse(response, false, "参数格式错误");
        } catch (Exception e) {
            e.printStackTrace();
            sendJsonResponse(response, false, "服务器错误");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String postIdStr = request.getParameter("postId");
        System.out.println("/comment?postId=" + request.getParameter("postId"));

        if (postIdStr == null || postIdStr.isEmpty()) {
            sendJsonResponse(response, false, "缺少postId参数");
            return;
        }

        try {
            int postId = Integer.parseInt(request.getParameter("postId"));
            List<Comment> comments = postService.getCommentsByPostId(postId);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            // 使用 Gson 序列化
            Gson gson = new Gson();
            String json = gson.toJson(comments);

            // 打印完整的JSON字符串到后端控制台，方便查看
            System.out.println("返回的评论JSON：" + json);

            PrintWriter out = response.getWriter();
            out.print(json);
            out.flush();

            System.out.println("获取到评论数量: " + comments.size());
            for (Comment c : comments) {
                System.out.println("评论内容: " + c.getContent());
            }
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

        } catch (NumberFormatException e) {
            sendJsonResponse(response, false, "参数格式错误");
        } catch (Exception e) {
            e.printStackTrace();
            sendJsonResponse(response, false, "服务器错误");
        }
    }

    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            sendJsonResponse(response, false, "请先登录");
            return;
        }

        String commentIdStr = request.getParameter("commentId");

        if (commentIdStr == null || commentIdStr.isEmpty()) {
            sendJsonResponse(response, false, "缺少commentId参数");
            return;
        }

        try {
            int commentId = Integer.parseInt(commentIdStr);
            boolean success = postService.deleteComment(commentId, currentUser.getUserId());
            sendJsonResponse(response, success, success ? "删除成功" : "删除失败");
        } catch (NumberFormatException e) {
            sendJsonResponse(response, false, "参数格式错误");
        } catch (Exception e) {
            e.printStackTrace();
            sendJsonResponse(response, false, "服务器错误");
        }
    }

    private void sendJsonResponse(HttpServletResponse response, boolean success, String message) throws IOException {
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", message);
        sendJsonResponse(response, result);
    }

    private void sendJsonResponse(HttpServletResponse response, Object data) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        out.print(gson.toJson(data));
        out.flush();
    }
}